document.addEventListener('DOMContentLoaded', function () {
    // 从 localStorage 获取 user 对象
    const user = JSON.parse(localStorage.getItem('loggedinUser'));
    const historyContainer = document.getElementById('historyContainer');

    function getOrdinalSuffix(day) {
        if (day >= 11 && day <= 13) {
            return 'th';
        }
        switch (day % 10) {
            case 1:
                return 'st';
            case 2:
                return 'nd';
            case 3:
                return 'rd';
            default:
                return 'th';
        }
    }

    if (user && user.loginTimes) {
        // 遍历 loginTimes 数组，为每个时间生成独立模块
        user.loginTimes.forEach((loginTime, index) => {
            // 创建日期对象
            const date = new Date(loginTime);
            const month = date.toLocaleString('en-US', { month: 'short' });
            // 获取日期
            const day = date.getDate();
            // 获取英文序数词后缀
            const suffix = getOrdinalSuffix(day);
            // 组合成目标格式
            const formattedDate = `${month} ${day}${suffix}`;

            // 创建 HTML 模块
            const historyItem = document.createElement('div');
            historyItem.className = 'col-md-6';
            historyItem.innerHTML = `
                <div class="row g-0 border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-200 position-relative">
                    <div class="col p-4 d-flex flex-column position-static">
                        <div class="mb-1 text-body-secondary"><h2>${formattedDate}</h2></div>
                        <p class="card-text mb-auto"></p>
                        <a href="#" class="delete-btn"><p class="card-text mb-auto">Click to delete</p></a>
                    </div>
                    <div class="col-auto d-none d-lg-block">
                        <svg class="bd-placeholder-img" width="200" height="250" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice"><title>Placeholder</title><rect width="100%" height="100%" fill="#d9e99f"/><text x="50%" y="50%" fill="#eceeef" dy=".3em"></text></svg>
                    </div>
                </div>
            `;

            const deleteBtn = historyItem.querySelector('.delete-btn');
            deleteBtn.addEventListener('click', function (e) {
                e.preventDefault();
                // 弹出确认删除的弹窗
                const isConfirmed = confirm('确定要删除这条记录吗？');
                if (isConfirmed) {
                    // 从 user 对象中删除对应登录时间
                    user.loginTimes.splice(index, 1);
                    // 更新 localStorage 中的 user 对象
                    localStorage.setItem('loggedinUser', JSON.stringify(user));
                    // 从 DOM 中移除当前历史记录项
                    historyItem.remove();
                }
            });

            // 将模块添加到容器中
            historyContainer.appendChild(historyItem);
        });
    }
});

function setupPunchPage() {
    const addStudentButton = document.getElementById('addStudentButton');
    if (addStudentButton) {
        addStudentButton.addEventListener('click', function () {
            // 获取当前日期
            const now = new Date();
            const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()).toISOString().split('T')[0];

            // 从本地存储获取点击记录
            let clickHistory = JSON.parse(localStorage.getItem('studyClickHistory')) || {};

            // 更新点击次数
            if (!clickHistory[today]) {
                clickHistory[today] = 1;
            } else {
                clickHistory[today]++;
            }

            // 将更新后的记录存回本地存储
            localStorage.setItem('studyClickHistory', JSON.stringify(clickHistory));
        });
    }
}

window.onload = function () {
    // 从本地存储获取 loggedinUser
    var user = JSON.parse(localStorage.getItem("loggedinUser"));
    if (user && user.history) {
        var historyList = document.getElementById("history-list");
        // 清空历史记录列表
        historyList.innerHTML = "";
        user.history.forEach(function (entry, index) {
            var listItem = document.createElement("li");
            listItem.className = "list-group-item d-flex justify-content-between align-items-center";
            listItem.textContent = entry.date;

            var deleteButton = document.createElement("button");
            deleteButton.className = "btn btn-warning btn-sm";
            deleteButton.textContent = "Delete";
            deleteButton.addEventListener('click', function () {
                // 删除本地存储中的记录
                user.history.splice(index, 1);
                localStorage.setItem("loggedinUser", JSON.stringify(user));
                // 从页面移除该记录
                listItem.remove();
            });

            listItem.appendChild(deleteButton);
            historyList.appendChild(listItem);
        });
    }
};

